package com.jstyle.jclifexd.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClient;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.haibin.calendarview.ExerciseRecodeData;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.jclifexd.BuildConfig;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.activity.ActivityHistoryActivity;
import com.jstyle.jclifexd.activity.BreathStartActivity;
import com.jstyle.jclifexd.activity.CountDownActivity;
import com.jstyle.jclifexd.activity.ExerciseModeActivity;
import com.jstyle.jclifexd.activity.ExerciseRecordListActivity;
import com.jstyle.jclifexd.activity.HealthHistoryActivity;
import com.jstyle.jclifexd.activity.HeartHistoryActivity;
import com.jstyle.jclifexd.activity.SleepHistoryActivity;
import com.jstyle.jclifexd.activity.TrackActivity;
import com.jstyle.jclifexd.adapter.ExerciseModeAdapter;
import com.jstyle.jclifexd.adapter.RecyclerViewBaseAdapter;
import com.jstyle.jclifexd.app.MyApplication;
import com.jstyle.jclifexd.ble.BleManager;
import com.jstyle.jclifexd.daoManager.HeartDataDaoManager;
import com.jstyle.jclifexd.daoManager.PathRecordDaoManager;
import com.jstyle.jclifexd.daoManager.SleepDataDaoManager;
import com.jstyle.jclifexd.daoManager.StepDataDaoManager;
import com.jstyle.jclifexd.model.Device1810;
import com.jstyle.jclifexd.model.Device181003;
import com.jstyle.jclifexd.model.Device1810G;
import com.jstyle.jclifexd.model.HeartData;
import com.jstyle.jclifexd.model.PathRecord;
import com.jstyle.jclifexd.model.SleepData;
import com.jstyle.jclifexd.model.SleepShowData;
import com.jstyle.jclifexd.model.StepData;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.ResolveData;
import com.jstyle.jclifexd.utils.RxBus;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.zyyoona7.popup.EasyPopup;
import com.zyyoona7.popup.XGravity;
import com.zyyoona7.popup.YGravity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ExerciseFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ExerciseFragment extends BaseFragment implements RecyclerViewBaseAdapter.OnItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.bt_exercise_title)
    Button btExerciseTitle;
    @BindView(R.id.iv_exercise_record)
    ImageView ivExerciseRecord;
    @BindView(R.id.RecyclerView_exercise)
    RecyclerView RecyclerViewExercise;
    Unbinder unbinder;
    @BindArray(R.array.mode_name)
    String[] modeName;
    @BindView(R.id.bt_sleep_month_pre)
    ImageView btSleepMonthPre;
    @BindView(R.id.bt_sleep_month_date)
    Button btSleepMonthDate;
    @BindView(R.id.bt_sleep_month_next)
    ImageView btSleepMonthNext;
    @BindView(R.id.ll_exercise_date)
    LinearLayout llExerciseDate;
    @BindView(R.id.CalendarView_sleep_Month)
    CalendarView CalendarViewSleepMonth;
    @BindView(R.id.bt_exercise_mode)
    Button btExerciseMode;

    @BindView(R.id.ll_bottom_sheet)
    LinearLayout llBottomSheet;
    @BindView(R.id.iv_exercise)
    ImageView ivExercise;
    @BindView(R.id.RL_EXERCISE_MODE)
    RelativeLayout RLEXERCISEMODE;
    @BindView(R.id.CalendarLayout_exercise)
    CalendarLayout CalendarLayoutExercise;
    private HashMap<String, SleepShowData> markHashMap = new HashMap<>();

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    //private BottomSheetBehavior<LinearLayout> behavior;
    private String thisMonth;
    private String[] monthDates;
    private AMapLocationClient aMapLocationClient;
    private int position;
    private EasyPopup mCirclePop;
    private Map<String, ExerciseRecodeData> mapExerciseRecode = new HashMap<>();
    private TextView tvDetailDate;
    private Button btDetailStep;
    private Button btDetailHeart;
    private Button btDetailExerciseMode;
    private Button btDetailSleep;
    private ConstraintLayout constraintLayout;
    public static final String KEY_QUERYDATE = "KEY_QUERYDATE";
    ExerciseModeAdapter homePageAdapter;
    public ExerciseFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ExerciseFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ExerciseFragment newInstance(String param1, String param2) {
        ExerciseFragment fragment = new ExerciseFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_exercise, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private static final String TAG = "ExerciseFragment";

    private void init() {

        CalendarViewSleepMonth.setOnViewChangeListener(new CalendarView.OnViewChangeListener() {
            @Override
            public void onViewChange(boolean isMonthView) {
                ivExercise.setImageResource(isMonthView ? R.drawable.exercise_up : R.drawable.exercisef_down);
            }
        });

        CalendarViewSleepMonth.setOnItemSelectedListener(new CalendarView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(Calendar calendar, int index,float x, float y) {
                Log.i(TAG, "onItemSelected: " + x + " " + y);
                showDetail(calendar, index,(int) x, (int) y);
            }
        });
        ScreenUtils.setTitleTypeface(btExerciseTitle);
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getActivity());
        List<String> list = Arrays.asList(modeName);

       // llBottomSheet.setVisibility(isHideExerciMode() ? View.GONE : View.VISIBLE);

         homePageAdapter = new ExerciseModeAdapter(list);
        RecyclerViewExercise.setLayoutManager(layoutManager);
        RecyclerViewExercise.setAdapter(homePageAdapter);
        homePageAdapter.setOnItemClickListener(this);


        // behavior = BottomSheetBehavior.from(llBottomSheet);
        //  behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        thisMonth = DateUtil.getMonthString("", DateUtil.this_month);
        monthDates = DateUtil.getThisMonth();
        showDate();


        /**
         * 如果退出了活动当前界面需要刷新状态
         */
        RxBus.getInstance().toObservable(String.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String bleData) {
                if (null != bleData) {
                    if (bleData.equals("reloadSPORT")) {
                        if(null!=homePageAdapter){
                            homePageAdapter.UPData();
                        }
                    } } }
        });
    }

    private void showDetail(Calendar calendar, int index,int x, int y) {
         String date = calendar.getYear() + "." + String.format("%02d", calendar.getMonth()) + "." + String.format("%02d", calendar.getDay());

        if (mCirclePop == null) {
            mCirclePop = EasyPopup.create()
                    .setContentView(getContext(), R.layout.dialog_exercise_detail)
                    //是否允许点击PopupWindow之外的地方消失
                    .setFocusAndOutsideEnable(true)
                    //允许背景变暗
                    .setBackgroundDimEnable(true)
                    //变暗的透明度(0-1)，0为完全透明
                    .setDimValue(0.4f)
                    //变暗的背景颜色
                    .apply();
            tvDetailDate = mCirclePop.findViewById(R.id.textView_date);
            btDetailStep = mCirclePop.findViewById(R.id.button_step);

            btDetailHeart = mCirclePop.findViewById(R.id.button_hr);
            btDetailSleep = mCirclePop.findViewById(R.id.button_sleep);
            btDetailExerciseMode = mCirclePop.findViewById(R.id.button_exercise);
             constraintLayout=mCirclePop.findViewById(R.id.ConstraintLayout_bg);
        }
        setListener(date);
        int bgId=R.drawable.bg_exercise_detail;
        int yGravity=0;
        int xGravity=0;
        int offX=0;
        int showHeight=mCirclePop.getHeight()+y+btExerciseTitle.getHeight()+btSleepMonthDate.getHeight()+ScreenUtils.dip2px(getContext(),20);
        int screenHeight=ScreenUtils.getScreenHeight(getContext());
        Log.i(TAG, "showDetail: "+showHeight+" "+screenHeight);
        if(showHeight>screenHeight){
            yGravity=YGravity.ALIGN_BOTTOM;
            if(index<3){
                bgId=R.drawable.bg_exercise_detail_down;
                xGravity= XGravity.CENTER;
                offX=x-btSleepMonthDate.getWidth()/2;
            }else if(index>3){
                bgId=R.drawable.bg_exercise_detail_rightdown;
                xGravity= XGravity.LEFT;
                offX=x-btSleepMonthDate.getWidth();
            }else{
                bgId=R.drawable.bg_exercise_centerdown;
                xGravity= XGravity.LEFT;
                offX=x;
            }
            mCirclePop.showAtAnchorView(btSleepMonthDate, yGravity,xGravity, offX, y+ScreenUtils.dip2px(getContext(),33));
        }else{
            yGravity=YGravity.BELOW;
            View anchor=null;
            if(index<3){
                yGravity=YGravity.ALIGN_TOP;

                bgId=R.drawable.bg_exercise_detail;
                xGravity=XGravity.ALIGN_LEFT;
                offX=x;
                anchor=CalendarViewSleepMonth;
            }else if(index>3){
                bgId=R.drawable.bg_exercise_detail_right;
                xGravity=XGravity.LEFT;
                offX=x-btSleepMonthDate.getWidth();
                anchor=btSleepMonthDate;
            }else{
                bgId=R.drawable.bg_exercise_center;
                xGravity=XGravity.LEFT;
                offX=x;
                anchor=btSleepMonthDate;
            }
            mCirclePop.showAtAnchorView(anchor,yGravity,xGravity , offX, y);
       }
        constraintLayout.setBackgroundResource(bgId);

        tvDetailDate.setText(date);
        ExerciseRecodeData exerciseRecodeData = mapExerciseRecode.get(date);
        if (exerciseRecodeData != null) {
            String stepValue=exerciseRecodeData.getStepValues();
            String sleepValue=exerciseRecodeData.getSleepValues();
            int totalHrValue=exerciseRecodeData.getTotalHrValue();
            int count=exerciseRecodeData.getCountHeartValue();
            int exerciseMode=exerciseRecodeData.getExerciseMode();//出现120的运动模式?
            btDetailHeart.setText(count==0?"--":totalHrValue/count+"");
            btDetailStep.setText(stepValue);
            btDetailSleep.setText(sleepValue);
            btDetailExerciseMode.setText(exerciseMode==-1||exerciseMode>=modeName.length?"--":modeName[exerciseMode]);
        } else {
            btDetailStep.setText("--");
            btDetailHeart.setText("--");
            btDetailExerciseMode.setText("--");
            btDetailSleep.setText("--");
        }
    }

    private void setListener(final String date){
        btDetailStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(ActivityHistoryActivity.class,KEY_QUERYDATE,date);
            }
        });
        btDetailSleep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(SleepHistoryActivity.class, KEY_QUERYDATE, date.substring(2));

            }
        });
        btDetailHeart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(HeartHistoryActivity.class, HealthHistoryActivity.KEY_DATA_DATE, date.substring(2));
            }
        });
        btDetailExerciseMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: "+date);
               //startActivity(ExerciseRecordListActivity.class);
            }
        });
    }
    private void showDate() {
        String monthDate = DateUtil.getShowMonthDate(getActivity(), monthDates[0]);
        btSleepMonthDate.setText(monthDate.contains("мая")?monthDate.replace("мая","май"):monthDate);
        btSleepMonthNext.setEnabled(DateUtil.monthEnable(getActivity(), monthDate));
        findAllData();
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.iv_exercise_record)
    public void onViewClicked() {
        //startActivity(CountDownActivity.class);
    }

    @OnClick({R.id.RL_EXERCISE_MODE, R.id.bt_sleep_month_pre, R.id.bt_sleep_month_next, R.id.iv_exercise_record,R.id.start_sport})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start_sport:
                if (BleManager.getInstance().isConnected()) {
                    startActivity(CountDownActivity.class, TrackActivity.key_ExerciseMode,  ExerciseMode.Mode_RUN);
                }else{
                    showToast(getString(R.string.Bluetooth_Disconnected));
                    return;
                }
                break;
            case R.id.bt_sleep_month_pre:
                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.last_month);
                monthDates = DateUtil.getLastMonth(monthDates[0]);
                if (!CalendarLayoutExercise.isExpand()) CalendarLayoutExercise.expand();
                CalendarViewSleepMonth.scrollToPre();
                showDate();
                break;
            case R.id.bt_sleep_month_next:
                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.next_month);
                monthDates = DateUtil.getNextMonth(monthDates[0]);
                if (!CalendarLayoutExercise.isExpand()) CalendarLayoutExercise.expand();
                CalendarViewSleepMonth.scrollToNext();
                showDate();
                break;
            case R.id.RL_EXERCISE_MODE:
                if (!CalendarLayoutExercise.isExpand()) {
                    CalendarLayoutExercise.expand();
                } else {
                    CalendarLayoutExercise.shrink();
                }
                break;
            case R.id.iv_exercise_record:
                Intent intent = new Intent(getContext(), ExerciseModeActivity.class);
                startActivityForResult(intent, 0);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            Log.i(TAG, "onActivityResult: ");
            findAllData();
        }
    }


    @Override
    public void onItemClick(int position) {
        for (int i=0;i<homePageAdapter.getItemCount();i++){
            if(position == i){
                ((RadioButton) RecyclerViewExercise.findViewWithTag(position)).setChecked(true);
            }else{
                ((RadioButton) RecyclerViewExercise.findViewWithTag(i)).setChecked(false);
            }
        }

        if (BleManager.getInstance().isConnected()) {
            if (position == 6) {
                startActivity(BreathStartActivity.class);
            } else {//1810g只有016
                if(MyApplication.getJstyleDevice() instanceof Device1810G){
                    if(position== ExerciseMode.Mode_RUN ||position==ExerciseMode.Mode_CYCLING){
                        startActivity(CountDownActivity.class, TrackActivity.key_ExerciseMode, position);
                    }else {
                        showToast(getString(R.string.device_notsupport_mode));
                    }
                }else {
                    startActivity(CountDownActivity.class, TrackActivity.key_ExerciseMode, position);
                }

            }
        }else{
            showToast(getString(R.string.Bluetooth_Disconnected));
            return;
        }

    }

    private boolean isHideExerciMode() {
        return BuildConfig.APPLICATION_ID.equals("com.jstyle.fomofit") && (MyApplication.getJstyleDevice() instanceof Device1810||MyApplication.getJstyleDevice() instanceof Device181003);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            findAllData();
            //llBottomSheet.setVisibility(isHideExerciMode() ? View.GONE : View.VISIBLE);

        }
    }
//    boolean startExercise;
//    public void enableExercise(String enable) {
//        int enableValue=Integer.valueOf(enable);
//        if(enableValue==1&&startExercise){
//            startExercise=false;
//        }
//    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void findAllData() {
        String mode = SharedPreferenceUtils.getString(SharedPreferenceUtils.KEY_Exercise_Mode, "0,1,2,3");
        List<Integer> checkedList = new ArrayList<>();
        Log.i(TAG, "findAllData: " + mode);
        markHashMap.clear();
        if (!TextUtils.isEmpty(mode)) {
            String[] modeArray = mode.split(",");
            for (String s : modeArray) {
                checkedList.add(Integer.valueOf(s));
            }
            if (checkedList.contains(2)) {
                mergeSleepData(checkedList);
            } else {
                updateCalendar(checkedList);
            }

        } else {
            CalendarViewSleepMonth.setExerciseRecodeData(new HashMap<String, ExerciseRecodeData>());
        }

    }

    private void mergeSleepData(final List<Integer> checkedList) {
        List<Observable<Integer>> observables = new ArrayList<>();
        for (String date : monthDates) {
            observables.add(getDayObservable(date));
        }
        showLoadingDialog();
        Observable.merge(observables).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer value) {
                Log.i(TAG, "onNext: " + value);
            }

            @Override
            public void onError(Throwable e) {
                disMissLoadingDialog();
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                disMissLoadingDialog();
                updateCalendar(checkedList);
            }
        });
    }

    private void initHeartData(Map<String, ExerciseRecodeData> map) {
        List<HeartData> heartDataList = HeartDataDaoManager.queryExerciseData(monthDates[0], monthDates[monthDates.length - 1]);
        for (HeartData heartData : heartDataList) {
            String date = "20" + heartData.getTime().split(" ")[0];
            ExerciseRecodeData calendar = map.get(date);
            if (calendar == null) calendar = new ExerciseRecodeData();
            int heart=heartData.getHeart();
            heart+=calendar.getTotalHrValue();
            calendar.setTotalHrValue(heart);
            int hrCount=calendar.getCountHeartValue();
            hrCount++;
            calendar.setCountHeartValue(hrCount);
            calendar.setHeartStatus(ExerciseRecodeData.HasData);
            map.put(date, calendar);
        }
    }

    private void initStepData(Map<String, ExerciseRecodeData> map) {
        List<StepData> stepDataList = StepDataDaoManager.queryData(monthDates[0], monthDates[monthDates.length - 1]);
        int stepGoal = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_Step_goal, 10000);
        for (StepData stepData : stepDataList) {
            String date = "20" + stepData.getDate().split(" ")[0];

            int step = Integer.parseInt(stepData.getStep());
            if(step!=0){
                ExerciseRecodeData calendar = map.get(date);
                if (calendar == null) calendar = new ExerciseRecodeData();
                calendar.setStepValues(stepData.getStep());
                calendar.setStepStatus(step >= stepGoal ? ExerciseRecodeData.HasData : ExerciseRecodeData.Data_Unfinished);
                map.put(date, calendar);
            }

        }
    }

    private void initExerciseData(Map<String, ExerciseRecodeData> map) {
        List<PathRecord> pathRecords = PathRecordDaoManager.getPathRecord(monthDates[0], monthDates[monthDates.length - 1]);
        for (PathRecord pathRecord : pathRecords) {
            String date = "20" + pathRecord.getMDate().split(" ")[0];
            ExerciseRecodeData calendar = map.get(date);
            if (calendar == null) {
                calendar = new ExerciseRecodeData();
                calendar.setExerciseMode(pathRecord.getExerciseMode());
            }
            calendar.setExercise(ExerciseRecodeData.HasData);
            map.put(date, calendar);
        }

    }

    private void updateCalendar(List<Integer> checkedList) {
        mapExerciseRecode = new HashMap<>();
        if (checkedList.contains(1)) initExerciseData(mapExerciseRecode);
        if (checkedList.contains(3)) initHeartData(mapExerciseRecode);
        if (checkedList.contains(0)) initStepData(mapExerciseRecode);
        float sleepGoal = SharedPreferenceUtils.getFloat(SharedPreferenceUtils.KEY_Sleep_goal, 8f)*60;

        for (Map.Entry<String, SleepShowData> entry : markHashMap.entrySet()) {
            String date = "20" + entry.getKey();
            SleepShowData sleepShowData = entry.getValue();
            float total = sleepShowData.getTotalTime() ;
            ExerciseRecodeData calendar = mapExerciseRecode.get(date);
            if (calendar == null) {
                calendar = new ExerciseRecodeData();
            }
            calendar.setSleepValues(DateUtil.getPointSleepTime(getActivity(), total));
            calendar.setSleepStatus(total >= sleepGoal ? ExerciseRecodeData.HasData : ExerciseRecodeData.Data_Unfinished);
            mapExerciseRecode.put(date, calendar);
        }
        CalendarViewSleepMonth.setExerciseRecodeData(mapExerciseRecode);
    }

    private Observable<Integer> getDayObservable(final String date) {
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) {
                String startDate = DateUtil.getTomorrowDateString(date);
                List<SleepData> sleepDataList = SleepDataDaoManager.queryData(date, startDate);
                int[] sleepData = getSleepData(sleepDataList, date);
                float[] showData = getShowSleepData(sleepData);
                List<Integer> sleepTime = getSleepTime(sleepData);
                int[] sleepLevel = new int[3];
                for (float value : showData) {
                    if (value != 0) sleepLevel[ResolveData.getSleepLevel((int) value)]++;
                }
                int duration=0;
                if (sleepTime.size() >= 2) {
                    int count = sleepTime.size() / 2;
                    for (int i = 0; i < count; i++) {
                        duration += sleepTime.get(i * 2 + 1) - sleepTime.get(i * 2);
                    }

                }
                //waitS();
                float deep = sleepLevel[0] * 5;
                float light = sleepLevel[1] * 5;
                float awake = sleepLevel[2] * 5;
                float total = duration*5;
                int id = ResolveData.getSleepQualityLevel(deep, light);
                SleepShowData sleepShowData = new SleepShowData();
                sleepShowData.setAwakeTime(awake );
                sleepShowData.setDate(date);
                sleepShowData.setDeepTime(deep );
                sleepShowData.setLightTime(light );
                sleepShowData.setTotalTime(total );
                sleepShowData.setSleepLevel(id);
                if (id != 0) markHashMap.put(date, sleepShowData);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io());

    }

    private int[] getSleepData(List<SleepData> sleepDataList, String startDate) {
        int[] fiveSleepData = new int[288];//288*5分钟
        for (int i = 0; i < fiveSleepData.length; i++) {
            fiveSleepData[i] = -1;//睡眠数据0为有效数据
        }
        for (SleepData sleepData : sleepDataList) {
            String time = sleepData.getTime();
            String data = sleepData.getDateString();
            int startCount = DateUtil.get5MIndex(time, startDate + " 12:00:00");
            if (startCount >= 288) break;
            fiveSleepData[startCount] = Integer.valueOf(data);
        }
        return fiveSleepData;
    }
    private List<Integer> getSleepTime(int[] fiveSleepData) {
        List<Integer> list = new ArrayList<>();
        int goBed = -1;
        int upBed = 0;
        int offCount = 0;
        for (int i = 0; i < fiveSleepData.length; i++) {
            int data = fiveSleepData[i];
            if (data != -1) {
                offCount = 0;
                if (goBed == -1) {
                    list.add(i);
                    goBed = i;
                }

            } else {
                offCount++;
                if (offCount == 6 && goBed != -1) {//30分钟离床
                    list.add(i - 5);
                    offCount = 0;
                    goBed = -1;
                }
            }
            if(i==fiveSleepData.length-1&&goBed!=-1){
                list.add(i);
            }
        }
        return list;
    }

    private float[] getShowSleepData(int[] fiveSleepData) {
        float[] showData = new float[fiveSleepData.length];
        int length = fiveSleepData.length;
        out:
        for (int i = 0; i < length; i++) {//取5分钟的平均值
            float total = 0;
            float count = 0;
            for (int j = 0; j < 5; j++) {
                int position = i + j;
                if (position < length) {
                    int data = fiveSleepData[position];
                    if (data != -1) {
                        total += data;
                        count++;
                    }
                } else {
                    showData[i] = count == 0 ? 0 : total / count;
                    continue out;
                }

            }
            showData[i] = count == 0 ? 0 : total / count;
        }
        return showData;
    }


}
